const baseUrl = 'https://huashenapi.saomaxing.com/';
const baseUrl1 = 'https://huashenapi.saomaxing.com';

// const baseUrl = 'http://localhost:824/';
// const baseUrl1 = 'http://localhost:824';

//图片访问地址
const imageUrl = 'https://images.saomaxing.com/';
//Qiniu 七牛云，SystemFile 服务器文件系统
const FileType = 'Qiniu';

//是否有token失效弹窗
let isLoginModalShown = false;

//产品相关配置
const projectName='华伸机电'
const projectDesc='二维码设备维保系统'



//百度应用
const clientId='O6NaH58t578thj1SD5N2hyl0';
const clientSecret='5845JuD2zOMuFdpmHyQoQRSOHHrRo3p3';

//七牛云
const QiNiuAccessKey='eQusCt1aFO14hy6kbvb-ozGhRXGbGmsFkrhJeJbl'
const QiNiuSecretKey='j3i7qdsXtZpwARl_2IdhoBI8OqCvX6MOWvO3TRaV'
const QiNiuNameSpace='huashenqiniu'

const qqMapKey = 'LIDBZ-7UALU-RJYVE-4I36N-QZSJO-DYFZX';

// 用于判断是否已弹出登录提示
//let isLoginPopupShown = false; 1


const getRequest= (path,name)=> {
    var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
    if (reg.test(path))
    return unescape(RegExp.$2.replace(/\+/g, " "));
    return "";
}

// 静默登录逻辑
const handleSilentLogin = (resolve, reject) => {
    // 触发静默登录
	uni.login({
		provider: 'weixin',
		success: function(res) {
			that.loginData.code=loginRes.code
			// 发起静默登录请求，传递code到后端
			uni.request({
			    url: baseUrl + 'api/UserLoginByOpenId', // 假设后端有此接口处理静默登录
			    method: 'POST',
			    data: {
			        code: res.code
			    },
			    success: (loginRes) => {
			        if (loginRes.data.code == 1) {
			            // 登录成功，重新获取token并存储
			            let userdata = loginRes.data.data;
			            uni.setStorageSync('userdata', userdata);
			            //isLoginPopupShown = false; // 恢复弹窗状态
			            resolve(loginRes);
			        } else {
			            uni.showModal({
			                title: '登录失败',
			                content: loginRes.data.message,
			                showCancel: false
			            });
			        }
			    },
			    fail: (error) => {
			        uni.showToast({
			            title: '登录失败',
			            icon: 'none'
			        });
			        reject(error);
			    }
			});
		},fail() { 
			//直接去用按钮登陆
		}
	});
};

// 不带token请求
const httpRequest = (opts, data) => {
	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.showToast({
				title: '网络连接不可用！',
				icon: 'none'
			});
		}
		return false
	});
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/json; charset=UTF-8'
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				resolve(res[1])
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};
//带Token请求
const httpTokenRequest = (opts, data) => {
	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.showToast({
				title: '网络连接不可用！',
				icon: 'none'
			});
		}
		return false
	});
	let token = uni.getStorageSync('userdata').token;

	// hadToken()
	if (token == '' || token == undefined || token == null) {
		if(opts.url!='api/AddUserPosition'&&opts.url!='api/getSceneCounts'){
			uni.hideLoading();
			if (!isLoginModalShown) 
			{
				isLoginModalShown = true;
				uni.showModal({
					title: '提示',
					content: '本地登录失效，请重新登录',
					showCancel: false, // 强制用户必须确认
					success: function (res) {
						if (res.confirm) {
							uni.reLaunch({
								url: '/pages/qrcode/login'
							});
							uni.clearStorageSync();
						}
					},
					complete: () => {
						isLoginModalShown = false; // 重置标志
					}
				});
			}
		}
	} 
	else 
	{
		let httpDefaultOpts = {
			url: baseUrl + opts.url,
			data: data,
			method: opts.method,
			header: opts.method == 'get' ? {
				'token': token,
				'X-Requested-With': 'XMLHttpRequest',
				"Accept": "application/json",
				"Content-Type": "application/json; charset=UTF-8"
			} : {
				'token': token,
				'X-Requested-With': 'XMLHttpRequest',
				'Content-Type': 'application/json; charset=UTF-8'
			},
			dataType: 'json',
		}
		let promise = new Promise(function(resolve, reject) {
			uni.request(httpDefaultOpts).then(
				(res) => {
					if (res[1].data.code == 1) {
						resolve(res[1])
					} else {
						if (res[1].data.code == 401) {
							if(opts.url!='api/AddUserPosition'&&opts.url!='api/getSceneCounts'){
								uni.hideLoading();
								if (!isLoginModalShown) {
									isLoginModalShown = true;
									uni.showModal({
										title: '提示',
										content: '账号已过期，请重新登录',
										showCancel: false,
										success: function (res) {
											if (res.confirm) {
												uni.reLaunch({
													url: '/pages/qrcode/login'
												});
												uni.clearStorageSync();
											}
										},
										complete: () => {
											isLoginModalShown = false; // 重置标志
										}
									});
								}
								// uni.showModal({
								// 	title: '提示',
								// 	content: '账号已过期，请重新登录',
								// 	success: function (res) {
								// 		if (res.confirm) {
								// 			setTimeout(() => {
								// 			      uni.reLaunch({
								// 			      	url: '/pages/qrcode/login'
								// 			      });
								// 			}, 0)
								// 			uni.clearStorageSync();
								// 		} 
								// 	}
								// });
							}
						} else {
							resolve(res[1])
						}
					}
				}
			).catch(
				(response) => {
					reject(response)
				}
			)
		})
		return promise
	}
	//let token = uni.getStorageSync('token')
	//此token是登录成功后后台返回保存在storage中的
};
//带Token请求本地不检测token
const httpTokenNotCheckRequest = (opts, data) => {
	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.showToast({
				title: '网络连接不可用！',
				icon: 'none'
			});
		}
		return false
	});
	let token = uni.getStorageSync('userdata').token;
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			'token': token,
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'token': token,
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/json; charset=UTF-8'
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				if (res[1].data.code == 1) {
					resolve(res[1])
				} else {
					if (res[1].data.code == 401) {
						if(opts.url!='api/AddUserPosition'&&opts.url!='api/getSceneCounts'){
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: '账号已过期，请重新登录',
								showCancel: false, // 强制用户必须确认
								success: function (res) {
									if (res.confirm) {
										setTimeout(() => {
										      uni.reLaunch({
										      	url: '/pages/qrcode/login'
										      });
										}, 0)
										uni.clearStorageSync();
									} 
								}
							});
						}
					} else {
						resolve(res[1])
					}
				}
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise

};

//带Token请求,本地，服务端都不校验token
const httpTokenALLNotCheckRequest = (opts, data) => {
	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.showToast({
				title: '网络连接不可用！',
				icon: 'none'
			});
		}
		return false
	});
	let token = uni.getStorageSync('userdata').token;
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			'token': token,
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'token': token,
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/json; charset=UTF-8'
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				if (res[1].data.code == 1) {
					resolve(res[1])
				} else {
					resolve(res[1])
				}
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise

};
const hadToken = () => {
	let token = uni.getStorageSync('userdata').token;
	console.log('本地登录失效')
	if (token == '' || token == undefined || token == null) {
		uni.hideLoading();
		uni.showModal({
			title: '提示',
			content: '本地登录失效，请重新登录',
			showCancel: false, // 强制用户必须确认
			success: function (res) {
				if (res.confirm) {
					setTimeout(() => {
					      uni.reLaunch({
					      	url: '/pages/qrcode/login'
					      });
					}, 0)
					uni.clearStorageSync();
				}
			}
		});
		return false;
	}
	return true
}
export default {
	baseUrl,
	baseUrl1,
	imageUrl,
	FileType,
	QiNiuAccessKey,
	QiNiuSecretKey,
	httpRequest,
	httpTokenRequest,
	hadToken,
	qqMapKey,
	getRequest,
	httpTokenNotCheckRequest,
	httpTokenALLNotCheckRequest,
	clientId,
	clientSecret,
	QiNiuNameSpace,
	projectName,
	projectDesc
}
